Grokking Google Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Google Easy
Add Binary (easy)
Solution: Add Binary
Valid Mountain Array (easy)
Solution: Valid Mountain Array
Set Mismatch (easy)
Solution: Set Mismatch
Is Subsequence (easy)
Solution: Is Subsequence
Length of Last Word (easy)
Solution: Length of Last Word
Search Insert Position (easy)
Solution: Search Insert Position
Repeated Substring Pattern (easy)
Solution: Repeated Substring Pattern
Monotonic Array (easy)
Solution: Monotonic Array
Count Nodes Equal to Average of Subtree (easy)
Solution: Count Nodes Equal to Average of Subtree
Find the Difference (easy)
Solution: Find the Difference
How Many Numbers Are Smaller Than the Current Number (easy)
Solution: How Many Numbers Are Smaller Than the Current Number
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Find the Difference of Two Arrays (easy)
Solution: Find the Difference of Two Arrays
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Gray Code (medium)
Solution: Gray Code
2 Keys Keyboard (medium)
Solution: 2 Keys Keyboard
Arithmetic Slices (medium)
Solution: Arithmetic Slices
Unique Length-3 Palindromic Subsequences (medium)
Solution: Unique Length-3 Palindromic Subsequences
Minimum Difference Between Largest and Smallest Value in Three Moves (medium)
Solution: Minimum Difference Between Largest and Smallest Value in Three Moves
Letter Combinations of a Phone Number (medium)
Solution: Letter Combinations of a Phone Number
01 Matrix (medium)
Solution: 01 Matrix
Maximum Points You Can Obtain from Cards (medium)
Solution: Maximum Points You Can Obtain from Cards
Strobogrammatic Number II (medium)
Solution: Strobogrammatic Number II
Maximum Length of Semi-Decreasing Subarrays (medium)
Solution: Maximum Length of Semi-Decreasing Subarrays
Minimum Area Rectangle (medium)
Solution: Minimum Area Rectangle
Count Unreachable Pairs of Nodes in an Undirected Graph (medium)
Solution: Count Unreachable Pairs of Nodes in an Undirected Graph
Single Number II (medium)
Solution: Single Number II
4Sum II (medium)
Solution: 4Sum II
Furthest Building You Can Reach (medium)
Solution: Furthest Building You Can Reach
Minimizing Array After Replacing Pairs With Their Product (medium)
Solution: Minimizing Array After Replacing Pairs With Their Product
Fair Distribution of Cookies (medium)
Solution: Fair Distribution of Cookies
Find Leaves of Binary Tree (medium)
Solution: Find Leaves of Binary Tree
Rotate Image (medium)
Solution: Rotate Image
Combination Sum (medium)
Solution: Combination Sum
Implement Trie (Prefix Tree) (medium)
Solution: Implement Trie (Prefix Tree)
Number of Islands (medium)
Solution: Number of Islands
Edit Distance (medium)
Solution: Edit Distance
Container With Most Water (Medium)
Solution: Container With Most Water
Meeting Rooms II (medium)
Solution: Meeting Rooms II
Shortest Subarray with Sum at Least K (hard)
Solution: Shortest Subarray with Sum at Least K
Reverse Pairs (hard)
Solution: Reverse Pairs
Nth Magical Number (hard)
Solution: Nth Magical Number
Candy (hard)
Solution: Candy
Arithmetic Slices II - Subsequence (hard)
Solution: Arithmetic Slices II - Subsequence
Burst Balloons (hard)
Solution: Burst Balloons
Sum of Distances in Tree (hard)
Solution: Sum of Distances in Tree
Maximum Score of a Good Subarray (hard)
Solution: Maximum Score of a Good Subarray
Trapping Rain Water (hard)
Solution: Trapping Rain Water
First Missing Positive (hard)
Solution: First Missing Positive
Solution: Length of Last Word

Problem Statement

Given a string str which contains words and spaces, return the length of the last word in the str.

A word is defined as a substring containing non-space characters only.

Examples

1.Example 1:

  • Input: str = "Fly to the moon"
  • Expected Output: 4
  • Justification: The last word is "moon" which consists of 4 characters.
  1. Example 2:
  • Input: str = "Java Programming 101 "
  • Expected Output: 3
  • Justification: The last word is "101" which consists of 3 characters. Note the trailing spaces are ignored.
  1. Example 3:
  • Input: str = " "
  • Expected Output: 0
  • Justification: There is no word in this string, only spaces.

Solution

To solve this problem, we adopt a straightforward yet effective strategy by analyzing the given string from its end towards the beginning. This approach allows us to directly locate and measure the last word, bypassing any preceding content or trailing spaces that do not contribute to the final count.

By employing a simple backward traversal, we efficiently find the end of the last word and then determine its length by counting the characters until a space or the start of the string is encountered.

Step-by-Step Algorithm

  1. Initialize Pointer: Set a pointer or index variable to the last position of the input string. This is used to traverse the string from the end towards the beginning.

  2. Skip Trailing Spaces: Move the pointer backwards (decrement the pointer) as long as the character at the current pointer position is a space. This step ensures that any trailing spaces are ignored when determining the length of the last word.

  3. Initialize Last Word Length Counter: Once trailing spaces are skipped, initialize a variable to count the length of the last word. Set this counter to 0 initially.

  4. Count the Length of the Last Word: Continue moving the pointer backwards (decrementing the pointer) and increment the last word length counter for each non-space character encountered. Stop if a space character is encountered, indicating the start of the last word has been reached, or if the beginning of the string is reached.

  5. Return Last Word Length: Once the start of the last word is identified or the beginning of the string is reached, return the last word length counter as the length of the last word.

Algorithm Walkthrough

Let's consider the input: str = "Fly to the moon".

  1. Initialize Pointer: Set the pointer to position 14 (the last character position in the string "Fly to the moon").

  2. Skip Trailing Spaces: There are no trailing spaces in this example, so the pointer remains at position 14 (character 'n').

  3. Initialize Last Word Length Counter: Set the last word length counter to 0.

  4. Count the Length of the Last Word:

    • Pointer at position 14 (character 'n'), increment counter to 1. Move pointer to position 13.
    • Pointer at position 13 (character 'o'), increment counter to 2. Move pointer to position 12.
    • Pointer at position 12 (character 'o'), increment counter to 3. Move pointer to position 11.
    • Pointer at position 11 (character 'm'), increment counter to 4. Move pointer to position 10.
    • Pointer at position 10 (character ' '), encounter a space, indicating the start of the last word has been found.
  5. Return Last Word Length: The last word length counter is 4, which is the length of the last word "moon". Return 4.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity:

The time complexity of this algorithm is , where n is the length of the input string. This is because, in the worst case, the algorithm might need to traverse the entire string once.

Space Complexity:

The space complexity is , which means constant space is used regardless of the input size.

Length of Last Word (easy)
Search Insert Position (easy)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity:

Space Complexity: